import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'  //静态导入

// //路由懒加载
const Home = () => import(/* webpackChunkName: "Home" */ '../views/list/Home.vue')

const Welcome = () => import(/* webpackChunkName: "Welcome" */ '../views/list/Welcome.vue')
// //用户模块
const Users = () => import(/* webpackChunkName: "Welcome" */ '../views/list/Users.vue')

//权限模块
const Rights = () => import(/* webpackChunkName: "Users_Rights_Roles" */ '../views/list/Rights.vue')

const Roles = () => import(/* webpackChunkName: "Users_Rights_Roles" */ '../views/list/Roles.vue')

//商品模块
const Categories = () => import(/* webpackChunkName: "Cate_Params" */ '../views/list/Categories.vue')

const Params = () => import(/* webpackChunkName: "Cate_Params" */ '../views/list/Params.vue')

//商品列表
const Goods = () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/list/Goods.vue')

const GoodsAdd = () => import(/* webpackChunkName: "GoodsList_Add" */ '../views/list/GoodsAdd.vue')

//订单模块
const Orders = () => import(/* webpackChunkName: "Order_Report" */ '../views/list/Orders.vue')

const Reports = () => import(/* webpackChunkName: "Order_Report" */ '../views/list/Reports.vue')


Vue.use(VueRouter)

const routes = [
  //项目正式路由开始
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect:'/users',
    children:[
      //写死的路由表，一般叫静态路由。还可以通过js生成这块，叫动态路由表
      { path: '/welcome',name: 'Welcome',component: Welcome},
      { path: '/users',name: 'Users',component: Users},
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Categories },
      { path: '/params', component: Params },
      { path: '/goods', component: Goods },
      { path: '/goods/add', component: GoodsAdd },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  //测试页面
    {
      path: '/test',
      name: 'Test',
      component: () =>import(/* webpackChunkName: "Test" */ '../views/Test.vue')
    },
    //找不到页面到都到login
   {
    path: '*',
    redirect: '/login'
   }
]
const router = new VueRouter({
  // mode:'history',  //history模式，打包上线时，需要服务器配合配置如果错误时挨边index.html
  routes
})

// 白名单-意思是不需要token，就可直接进入的页面
const whiteList = ['/login','/test']

//路由拦截-1.先看看有没有登录过token值，如果登录过放行 2.没有登录在次判断是否在登录页面
  
  router.beforeEach((to,from,next)=>{
        //有token或没token
        let token=localStorage.getItem('token')
        //有token放行
        if(token){
           next()
        }
        //注意这里没token又分2种情况 1.在登录页/或者其它不不需要token页面放行 2.否则去登录页
        else{
            // if(to.path=="/login"){
            if(whiteList.indexOf(to.path)!=-1){      
                 next()
            }
            else {
                  next('/login')
            }
        }
  })


export default router
